<?php

namespace App\Recharge\Api;

use App\Models\InterfaceConfiguration;
use App\Recharge\Bean\ApiNotifyDataBean;
use App\Recharge\Bean\BasicInformation;
use Illuminate\Http\Request;

class Chengjuan extends AbstractApi
{
    /**
     * @inheritDoc
     */
    public function rechargeData(BasicInformation $bean): array
    {
        $array = [
            'timestamp'         => millisecondTimestamp(),
            'app_id'            => $bean->getSupplierNum(), //商户号
            'order_no'          => $bean->getOrderNo(), //订单号
            'recharge_number'   => $bean->getAccount(), //充值账号
            'product_id'        => $bean->getGoodsId(), //商品编码
            'amount'            => $bean->getRechargeNum() * $bean->getStartCharging(),
            'ip'                => $bean->getIp(),//获取用户当前的ip
            'notify_url'        => $bean->getNotifyUrl(), //异步回调地址
            'version'           => '1.0.0',
            'customer_price'    => $bean->getUnitPrice() * 100,
        ];
        $array['sign'] = $this -> sign($array,$bean -> getSecretKey());
        return $array;
    }

    /**
     * @param array $array
     * @param string $secret_key
     * @return string
     */
    public function sign(array $array, string $secret_key){
        ksort($array);
        $data_url = urldecode(http_build_query($array));
        $md5_str  = $data_url.'&key='. $secret_key;
        $str      = md5($md5_str);
        return   strtoupper($str);
    }
    /**
     * @param InterfaceConfiguration $api
     * @param Request $request
     * @return ApiNotifyDataBean
     */
    public function apiNotifyLogic(InterfaceConfiguration $api, Request $request): ApiNotifyDataBean
    {
        $status = $request->input('state', '');
        $order_sn = $request->input('order_no', '');
        return $this->apiNotifyData($order_sn, $status)->setExecute(in_array($status, ['SUCCESS', 'FAILURE']))->setRechargeSuccess($status == 'SUCCESS');
    }

    /**
     * @param InterfaceConfiguration $config
     * @param BasicInformation $bean
     * @return array|mixed
     */
    public function balance(InterfaceConfiguration $config, BasicInformation $bean){
        $array = [
            'timestamp' =>getMsecTime(),
            'app_id' => $bean ->getSupplierNum()
        ];
        $array['Sign'] = $this->sign($array, $bean->getSecretKey());
        $res = curlcheng_post($config -> balance_url,$array);
        return data_get(json2array($res), $config->balance_title, 0);
    }
}
